package com.itheima.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao_scg;
import com.itheima.dao.OrderDao_scg;
import com.itheima.dao.OrderSettingDao_scg;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService_scg;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService_scg.class)
@Transactional
public class OrderServiceImpl_scg implements OrderService_scg {

    @Autowired
    private OrderSettingDao_scg orderSettingDao;
    @Autowired
    private MemberDao_scg memberDao;

    @Autowired
    private OrderDao_scg orderDao;


    @Override
    public Result order(Map map) throws Exception {

        //检查当前日期是否进行了预约设置
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);

        if (orderSetting == null) {

            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //检查预约日期是否预约已满
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations > number) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);

        ////判断是否在重复预约
        if (member != null) {
            Integer memberId = member.getId();
            int setmealId = Integer.parseInt((String)
                    map.get("setmealId"));
            Order order = new Order(memberId, date, null, null, setmealId);
            List<Order> list = orderDao.findByCondition(order);
            if (list != null && list.size() > 0) {
                //已经完成了预约，不能重复预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }

        } else {
            //检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);//自动完成会员注册

        }

        //预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//套餐ID
        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    @Override
    public Map findById(Integer id) throws Exception {

        Map map = orderDao.findById4Detail(id);

        if (map != null) {
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));
        }
        return map;
    }

    @Override
    public PageResult findOrderAndMember(QueryPageBean queryPageBean) {

        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

//        PageHelper.startPage(currentPage,pageSize);

        if (queryString != null && queryString.length() > 0) {
            PageHelper.startPage(currentPage, pageSize);
            Page<Map> listPage = orderDao.findOrderAndMember(queryString);
            Long sum = orderDao.findOrderAndMember2(queryString);
            for (Map map : listPage) {
                if (map.get("orderStatus").equals("未到诊")) {
                    map.put("flag", false);
                } else {
                    map.put("flag", true);
                }

            }
            return new PageResult(sum, listPage.getResult());
        } else {
            PageHelper.startPage(currentPage, pageSize);
            Page<Map> listPage = orderDao.findAll();
            for (Map map : listPage) {
                if (map.get("orderStatus").equals("未到诊")) {
                    map.put("flag", false);
                } else {
                    map.put("flag", true);
                }

            }
            Long sum = orderDao.findAll2();
            listPage.setTotal(sum);
            return new PageResult(sum, listPage.getResult());
        }


    }

    @Override
    public Result add(Map map, int[] setmeal_ids) throws Exception {

        //取出前台传的数据
        String name = (String) map.get("name");
        String idCard = (String) map.get("idCard");
        String phoneNumber = (String) map.get("phoneNumber");
        String sex = (String) map.get("sex");
//        Date orderDate = DateUtils.parseString2Date((String) map.get("orderDate"));


        //检查当前日期是否进行了预约设置
        String orderDate = (String) map.get("orderDate");
        String[] ts = orderDate.split("T");
        Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(ts[0]);
        long l = parse.getTime() + 1000 * 60 * 60 * 24;
        Date date = new Date(l);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);

        if (orderSetting == null) {

            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //检查预约日期是否预约已满
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations > number) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);

        ////判断是否在重复预约
        if (member != null) {
            Integer memberId = member.getId();
            int setmealId = Integer.parseInt((String)
                    map.get("setmealId"));
            Order order = new Order(memberId, date, null, null, setmealId);
            List<Order> list = orderDao.findByCondition(order);
            if (list != null && list.size() > 0) {
                //已经完成了预约，不能重复预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }

        } else {
            //检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName(name);
            member.setPhoneNumber(phoneNumber);
            member.setIdCard(idCard);
            member.setSex(sex);
            member.setRegTime(new Date());

            memberDao.add(member);//自动完成会员注册

        }

        //预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType("电话预约");//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        for (int setmeal_id : setmeal_ids) {
            order.setSetmealId(setmeal_id);//套餐ID
        }
        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
        orderSettingDao.editReservationsByOrderDate(orderSetting);


        return new Result(true, "预约成功");

    }


    @Override
    public void update(Map map, int[] ids) {

        String name = (String) map.get("name");//姓名
        int oid = (int) map.get("id");
        String phoneNumber = (String) map.get("phoneNumber");//手机号
        String sex = (String) map.get("sex");//性别
        String orderDate = (String) map.get("orderDate");//预约日期
        String[] ts = orderDate.split("T");
        Date parse = null;
        try {
            parse = new SimpleDateFormat("yyyy-MM-dd").parse(ts[0]);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long l = parse.getTime() + 1000 * 60 * 60 * 24;
        Date date = new Date(l);
        String orderType = (String) map.get("orderType");//预约类型
        String orderStatus = (String) map.get("orderStatus");//预约状态

        int member_id = orderDao.findById(oid);

        memberDao.update(name, phoneNumber, sex,member_id);
        for (int id : ids) {
            orderDao.update(date, orderType, orderStatus, id);

        }
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
        orderSettingDao.editReservationsByOrderDate(orderSetting);
    }

    @Override
    public Map find(int id) {
        return orderDao.find(id);
    }

    @Override
    public void delete(int id) {
        Date date = orderDao.findDete(id);
        orderDao.deleteById(id);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        orderSetting.setReservations(orderSetting.getReservations() - 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);

    }

    @Override
    public void updateOrderStatus(int id, boolean flag) {

        String orderStudus;
        if (flag) {

            orderStudus = "已到诊";
            orderDao.updateOrderStatus(id, orderStudus);
        } else {
            orderStudus = "未到诊";
            orderDao.updateOrderStatus(id, orderStudus);
        }

    }



}
